<script lang="ts" setup>
import type { SettlementInfo } from '@/api/types/finance'
import type { InfoItem } from '@/components/DetailCard.vue'
import { onLoad } from '@dcloudio/uni-app'
import { computed, ref } from 'vue'
import { useRoute } from 'vue-router'
import { getSysSettlementDetails } from '@/api/finance'
import ApprovalActionBar from '@/components/ApprovalActionBar.vue'
import DetailCard from '@/components/DetailCard.vue'
import { useFlow } from '@/hooks/useFlow'

definePage({
  style: {
    navigationBarTitleText: '支付定金详情',
  },
})

// 获取页面参数
const route = useRoute()
const processInstanceId = computed(() => route.params.processInstanceId as string || '')
const taskId = computed(() => route.params.taskId as string || '')

// 使用流程hook
const {
  currentProcess,
  getProcessInstance,
  getCurrentUserPendingTaskId,
  loading: flowLoading,
} = useFlow()

// 业务ID
const businessId = computed(() => {
  if (currentProcess.value?.businessKey) {
    return currentProcess.value.businessKey
  }
  if (currentProcess.value?.formVariables?.BUSINESS_KEY) {
    return currentProcess.value.formVariables.BUSINESS_KEY
  }
  return ''
})

// 业务详情数据
const businessDetail = ref<SettlementInfo | null>(null)
const businessLoading = ref(false)
const businessError = ref('')
const flowId = ref<string>('')
const flowIdValue = ref<string>('')
const idValue = ref<string>('')

// 定金基本信息卡片数据
const basicInfoList = computed<InfoItem[]>(() => {
  const data = businessDetail.value
  if (!data)
    return []
  return [
    {
      label: '结算单号',
      key: 'settlementNo',
      value: data.settlementNo || '-',
    },
    {
      label: '定金金额',
      key: 'amount',
      value: data.amount || 0,
      type: 'currency' as const,
    },
    {
      label: '支付方式',
      key: 'paymentMethod',
      value: data.paymentMethod || '-',
    },
    {
      label: '支付状态',
      key: 'paymentStatus',
      value: data.paymentStatus || '-',
    },
    {
      label: '支付时间',
      key: 'paymentTime',
      value: data.paymentTime || '-',
      type: 'datetime' as const,
    },
  ]
})

// 关联业务信息卡片数据
const businessInfoList = computed<InfoItem[]>(() => {
  const data = businessDetail.value
  if (!data)
    return []

  const infoList: InfoItem[] = [
    {
      label: '业务ID',
      key: 'businessId',
      value: data.businessId || '-',
    },
    {
      label: '业务类型',
      key: 'businessType',
      value: data.businessType || '-',
    },
  ]

  // 如果有关系方信息，添加到列表中
  if (data.relatedPartyInfo) {
    Object.entries(data.relatedPartyInfo).forEach(([key, value]) => {
      infoList.push({
        label: key,
        key,
        value: typeof value === 'object' ? JSON.stringify(value) : value || '-',
        forceMultiline: typeof value === 'object',
      })
    })
  }

  return infoList
})

// 时间信息卡片数据
const timeInfoList = computed<InfoItem[]>(() => {
  const data = businessDetail.value
  if (!data)
    return []
  return [
    {
      label: '创建时间',
      key: 'createTime',
      value: data.createTime || '-',
      type: 'datetime' as const,
    },
    {
      label: '更新时间',
      key: 'updateTime',
      value: data.updateTime || '-',
      type: 'datetime' as const,
    },
  ]
})

// 流程信息卡片数据
const processInfoList = computed<InfoItem[]>(() => {
  if (!currentProcess.value)
    return []
  return [
    {
      label: '流程名称',
      key: 'name',
      value: currentProcess.value.name || '-',
    },
    {
      label: '流程状态',
      key: 'status',
      value: currentProcess.value.status === 1 ? '进行中' : '已结束',
    },
  ]
})

// 获取流程实例信息
async function fetchProcessInfo(id: string) {
  try {
    await getProcessInstance(id)
    // 获取当前用户待审批任务ID
    const taskId = await getCurrentUserPendingTaskId(idValue.value)
    if (taskId) {
      flowIdValue.value = taskId
    }
    // 从流程实例中提取节点信息
    if (currentProcess.value?.processDefinition) {
      console.log('流程定义信息:', currentProcess.value.processDefinition)
    }

    // 流程信息获取成功后，自动获取业务详情
    if (businessId.value) {
      await fetchPaymentOfDepositDetail()
    }
  }
  catch (error) {
    console.error('获取流程信息失败:', error)
    uni.showToast({
      title: '获取流程信息失败',
      icon: 'none',
    })
  }
}

// 获取支付定金详情
async function fetchPaymentOfDepositDetail() {
  if (!businessId.value) {
    return
  }

  businessLoading.value = true
  businessError.value = ''

  try {
    const res = await getSysSettlementDetails(businessId.value)
    businessDetail.value = res.data || null
  }
  catch (error) {
    console.error('获取支付定金详情失败:', error)
    businessError.value = '获取支付定金详情失败'
    uni.showToast({
      title: '获取支付定金详情失败',
      icon: 'none',
    })
  }
  finally {
    businessLoading.value = false
  }
}

// 页面加载时获取数据
onLoad((e: any) => {
  console.log('页面参数:', e)
  if (e.flowId) {
    flowId.value = e.flowId
    flowIdValue.value = e.flowId
  }
  idValue.value = e.id || ''
  if (!e.id) {
    uni.showToast({
      title: '没有获取到id',
      icon: 'none',
    })
    return
  }
  fetchProcessInfo(e.id)
})
</script>

<template>
  <view class="page p-4">
    <!-- 审批状态卡片 -->
    <ApprovalStatusCard :current-process="currentProcess" :id-value="idValue" />
    <!-- 加载状态 -->
    <view v-if="flowLoading || businessLoading" class="flex flex-col items-center justify-center py-10">
      <view class="text-gray-500">
        加载中...
      </view>
    </view>

    <!-- 业务详情展示 -->
    <view v-else-if="businessDetail" class="space-y-4">
      <!-- 定金基本信息卡片 -->
      <DetailCard
        title="定金基本信息"
        :info-list="basicInfoList"
      />

      <!-- 关联业务信息卡片 -->
      <DetailCard
        title="关联业务信息"
        :info-list="businessInfoList"
      />

      <!-- 时间信息卡片 -->
      <DetailCard
        title="时间信息"
        :info-list="timeInfoList"
      />

      <!-- 流程信息卡片 -->
      <DetailCard
        title="流程信息"
        :info-list="processInfoList"
      />
    </view>

    <!-- 错误状态 -->
    <view v-else-if="businessError" class="py-10 text-center text-gray-500">
      {{ businessError }}
      <button class="mt-3 text-blue-500" @click="fetchProcessInfo">
        重新获取
      </button>
    </view>

    <!-- 无数据状态 -->
    <view v-else class="py-10 text-center text-gray-500">
      暂无业务信息
    </view>

    <!-- 审批操作栏组件 -->
    <ApprovalActionBar
      v-if="flowIdValue && currentProcess?.status === 1"
      :process-id="flowIdValue"
    />
  </view>
</template>

<style lang="scss" scoped>
// 页面样式
.page {
  padding-bottom: 80px; // 为底部操作栏留出空间
}
</style>
